package com.hu.web.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;

public class ThirdServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取请求头信息
        String header = request.getHeader("User-Agent");
        System.out.println("header: " + header);
        String referer = request.getHeader("Referer");
        System.out.println("referer: " + referer);
        // 获取 URL 的路径信息
        String contextPath = request.getContextPath(); // 获取上下文路径
        System.out.println("contextPath: " + contextPath);
        String serverName = request.getServerName(); // 获取主机名
        System.out.println("serverName: " + serverName);
        int serverPort = request.getServerPort(); // 获取端口号
        System.out.println("serverPort: " + serverPort);
        String method = request.getMethod();
        System.out.println("method: " + method); // 获取请求方式
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {
        // 获取请求参数
        // 根据 key 值返回一个 value
        String username = request.getParameter("username");
        System.out.println("username: " + username);
        String password = request.getParameter("password");
        System.out.println("password: " + password);
        String gender = request.getParameter("gender");
        System.out.println("gender: " + gender);
        // 根据 key 值返回多个 value
        String[] hobbies = request.getParameterValues("hobby");
        for (String hobby: hobbies){
            System.out.println("hobby: " + hobby);
        }
        // 将整个表单的所有数据都放在 map 集合内
        Map<String, String[]> parameterMap = request.getParameterMap();
        Set<String> keySet = parameterMap.keySet();
        for(String key : keySet){
            System.out.println("key: " + key);
            System.out.println("value: " + Arrays.toString(parameterMap.get(key)));
        }

    }

}
